const multer = require('multer');
const path = require("path");
const fs = require('fs');
const { exec } = require('child_process');

const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, path.join(__dirname, "../../source_map/")); // 确保这个文件夹已经存在
    },
    filename(req, file, cb) {
        console.log("🚀 ~ filename ~ file:", file, req.body);
        //需要拼接文件的后缀名，以便我们返回给前端进行预览
        cb(null, file.originalname);
    },
})

const upload = multer({ storage: storage });

module.exports = app => {
    var router = require("express").Router();

    router.post('/uploadSourcemap', upload.single('file'), (req, res) => {
        const reqBody = {...req.body}
        console.log(reqBody, typeof reqBody, reqBody.appID)
        if (!req.file ) {
            return res.status(400).send('No file uploaded.');
        }
        
        const { appID } = reqBody
        if (!appID) {
            return res.status(500).send('No appID.');
        }
        const basePath = '../../source_map'
        
        const tarfile = path.join(__dirname, `${basePath}/temp_${appID}.tar.gz`)
        // 要检查和删除的文件夹路径
        const folderPath = path.join(__dirname, `${basePath}/${appID}`);
        
        // http://localhost:8080/IAM555/js/app.9daaa455.js.map
        // 检查文件夹是否存在
        fs.access(folderPath, fs.constants.F_OK, (err) => {
            let hasDir = true;
            if (err) {
                hasDir = false;
            }
            // 有文件夹则先删除
            if (hasDir) {
                const result = fs.rmdirSync(folderPath, { recursive: true })
                console.log("result", result)
            }
            // fs.mkdirSync(folderPath)
        
            exec(`tar -xzf ${tarfile} -C ${path.join(__dirname, basePath)}`, (err, stdout, stderr) => {
            if (err) {
                console.error('解压失败', err);
            } else {
                console.log('解压完成');
            }
        });
    
    });

        res.send('File uploaded successfully.');
    });

    app.use('/', router);
};
  







